package com.ruoyi.system.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.domain.SmsResult;
import com.ruoyi.system.core.SmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * SMS短信服务控制器
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    private static final Logger log = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送验证码（自动生成）
     */
    @PostMapping("/sendCode")
    public R<String> sendCode(@RequestParam String phoneNumber) {
        System.out.println("发送验证码请求: 手机号=" + phoneNumber);
        try {
            log.info("发送验证码请求: 手机号={}", phoneNumber);
            SmsResult result = smsService.sendVerificationCode(phoneNumber);
            
            if (result.getSuccess()) {
                    String codeKey = "sms:code:" + phoneNumber;
                    redisTemplate.opsForValue().set(
                            codeKey,
                            result.getVerificationCode(),
                            100000,
                            TimeUnit.MINUTES
                    );
                log.info("验证码发送成功: 手机号={}", phoneNumber);
                return R.ok("验证码发送成功", result.getVerificationCode());
            } else {
                log.warn("验证码发送失败: 手机号={}, 原因={}", phoneNumber, result.getMessage());
                return R.fail(result.getMessage());
            }
        } catch (Exception e) {
            log.error("发送验证码异常: 手机号={}, 错误={}", phoneNumber, e.getMessage(), e);
            return R.fail("系统异常，请稍后重试");
        }
    }

    /**
     * 发送验证码（指定验证码）
     */
    @PostMapping("/sendCodes")
    public R<String> sendCodes(@RequestParam String phoneNumber, 
                              @RequestParam String code) {
        try {
            log.info("发送指定验证码请求: 手机号={}, 验证码={}", phoneNumber, code);
            SmsResult result = smsService.sendVerificationCode(phoneNumber, code);
            
            if (result.getSuccess()) {
                log.info("指定验证码发送成功: 手机号={}", phoneNumber);
                return R.ok("验证码发送成功", result.getVerificationCode());
            } else {
                log.warn("指定验证码发送失败: 手机号={}, 原因={}", phoneNumber, result.getMessage());
                return R.fail(result.getMessage());
            }
        } catch (Exception e) {
            log.error("发送指定验证码异常: 手机号={}, 错误={}", phoneNumber, e.getMessage(), e);
            return R.fail("系统异常，请稍后重试");
        }
    }

    /**
     * 校验验证码
     */
    @PostMapping("/verify")
    public R<String> verify(@RequestParam String phoneNumber, 
                           @RequestParam String code) {
        try {
            log.info("验证码校验请求: 手机号={}, 验证码={}", phoneNumber, code);
            boolean isValid = smsService.verifyCode(phoneNumber, code);
            
            if (isValid) {
                smsService.deleteCode(phoneNumber);
                log.info("验证码校验成功: 手机号={}", phoneNumber);
                return R.ok("验证成功");
            } else {
                log.warn("验证码校验失败: 手机号={}, 验证码={}", phoneNumber, code);
                return R.fail("验证码错误或已过期");
            }
        } catch (Exception e) {
            log.error("验证码校验异常: 手机号={}, 错误={}", phoneNumber, e.getMessage(), e);
            return R.fail("系统异常，请稍后重试");
        }
    }

    /**
     * 获取短信发送状态
     */
    @GetMapping("/status")
    public R<String> getStatus(@RequestParam String phoneNumber) {
        try {
            return R.ok("短信服务正常");
        } catch (Exception e) {
            log.error("获取短信状态异常: 手机号={}, 错误={}", phoneNumber, e.getMessage(), e);
            return R.fail("系统异常，请稍后重试");
        }
    }
}
